import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { Card, Breadcrumb, Form, Button, Radio, DatePicker, Select } from 'antd'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { http } from '@/utils'

const { Option } = Select
const { RangePicker } = DatePicker

function Search({ search }) {
  const [channels, setChannels] = useState([])
  useEffect(() => {
    (async function() {
      const { data } = await http.get('/api/article/channels')
      if (data) {
        setChannels(data)
      }
    })()
  }, [])

  const onSearch = (values) => {
    const { status, channel, date } = values
    const _params = {}
    _params.status = status
    if (channel)  _params.channel = channel
    if (date) {
      _params.pubdateStart = date[0].format('YYYY-MM-DD')
      _params.pubdateEnd = date[1].format('YYYY-MM-DD')
    }
    // 修改params参数，触发接口再次发起
    search(_params)
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to='/'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{status: 0}} layout="inline" onFinish={onSearch}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={0}>全部</Radio>
              <Radio value={1}>草稿</Radio>
              <Radio value={2}>已发布</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="主题" name="channel">
            <Select placeholder="请选择主题" style={{width: 120}}>
              {
                channels.length && channels.map(channel =>
                  <Option value={channel.value} key={channel.id}>{channel.label}</Option>
                )
              }
            </Select>
          </Form.Item>
          <Form.Item label="日期" name="date">
            {/* 传入locale属性，控制中文显示 */}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit' style={{ marginLeft: 80 }}>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Search